<?php
/**
 * @Author:      ZH
 * @DateTime:    2016-2-16 15:32:48
 * @Description: 用于 pms 系统供货商管理
 */
class PMSSupplierController extends BaseController {
    /**
     *  列表
     * */
    public function supplierList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "page"=>'integer',
                "page_size"=>'integer',
                "purchase_type"=>'integer',
                "purchase_status"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $page_size = Input::get("page_size",25);
            $page = Input::get("page",1);

            $sls = MaintenanceSupplier::orderBy('id','desc');
            if(Input::get("name") != ""){
                $sls->where("name","like",'%'.Input::get("name").'%');
            }
            if(Input::get("purchase_type") != ""){
                $sls->where("purchase_type",Input::get("purchase_type"));
            }
            if(Input::get("purchase_status") != ""){
                $sls->where("purchase_status",Input::get("purchase_status"));
            }

            $count = $sls->count();
            $sls = $sls->skip($page_size*($page-1))->take($page_size)->get();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["count"=>$count,"lists"=>$sls],
                'extra'=>['purchase_types'=>MaintenanceSupplier::$purchase_types,'purchase_statuss'=>MaintenanceSupplier::$purchase_statuss]);
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     *  更改采购状态
     * */
    public function statusSupplier(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "status"=>'required|integer',
                "id"=>'required|integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $ms = MaintenanceSupplier::find(Input::get("id"));
            if(!$ms){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            $old = clone $ms;
            $ms->purchase_status = Input::get("status");
            try{
                $ms->save();
                PmsOpLog::write('supplier',Input::get("id"),'update','用户:' . $res['user']->id . ',更改采购状态,原状态:' . $old->purchase_status . ',新状态:' . Input::get("status"),json_encode($old),json_encode(MaintenanceSupplier::find(Input::get("id"))),$res['user']->id);
                break;
            }catch (Exception $e) {
                Log::error("error", array("system" => "pms" ,"event" => "statusSupplier", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("pms_error.supplier_update_error_30002");
                break;
            }
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     *  更改供货商编码
     * */
    public function setSupplierBm(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "bm"=>'required',
                "id"=>'required|integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $ms = MaintenanceSupplier::find(Input::get("id"));
            if(!$ms){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            $old = clone $ms;
            $ms->bm = Input::get("bm");
            try{
                $ms->save();
                PmsOpLog::write('supplier',Input::get("id"),'update','用户:' . $res['user']->id . ',更改供应商编码,原编码:' . $old->bm . ',新编码:' . Input::get("bm"),json_encode($old),json_encode(MaintenanceSupplier::find(Input::get("id"))),$res['user']->id);
                break;
            }catch (Exception $e) {
                Log::error("error", array("system" => "pms" ,"event" => "setSupplierBm", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("pms_error.supplier_update_error_30002");
                break;
            }
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "setSupplierBm", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     *  更改供货商采购类型
     * */
    public function setSupplierType(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "type"=>'required',
                "id"=>'required|integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $ms = MaintenanceSupplier::find(Input::get("id"));
            if(!$ms){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            $old = clone $ms;
            $ms->purchase_type = Input::get("type");
            try{
                $ms->save();
                PmsOpLog::write('supplier',Input::get("id"),'update','用户:' . $res['user']->id . ',更改供应商采购类型,愿类型:' . $old->purchase_type . ',新类型:' . $ms->purchase_type,json_encode($old),json_encode(MaintenanceSupplier::find(Input::get("id"))),$res['user']->id);
                break;
            }catch (Exception $e) {
                Log::error("error", array("system" => "pms" ,"event" => "setSupplierType", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("pms_error.supplier_update_error_30002");
                break;
            }
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "setSupplierType", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * 查看详情
     */
    public function getOne(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "id"=>'required|integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $ms = MaintenanceSupplier::find(Input::get("id"));
            if(!$ms){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            $response['result'] = $ms;
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "getOne", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * 保存，新建、修改
     */
    public function storeOne(){
        $rules = array(
            'token' => 'required',
//            "id"=>'integer',
//            "industry_type"=>'required|between:1,100',
//            "operating_address"=>'required|between:1,100',
//            "address"=>'required|between:1,100',
//            "scope"=>'required|between:1,100',
//            "country"=>'required|between:1,100',
//            "juridical"=>'required|between:1,100',
//            "contacts"=>'required|between:1,100',
//            "contacts_number"=>'integer|max:100000000000',
//            "fax"=>'integer|max:100000000000',
//            "postcode"=>'integer|max:100000000000',
//            "other_info"=>'between:1,100',
//            "gather_bank"=>'required|between:1,100',
//            "gather_account"=>'required|integer|max:1000000000000000000000000000000',
//            "bank"=>'required|between:1,100',
//            "account"=>'required|integer|max:1000000000000000000000000000000',
//            "taxpayer"=>'required|between:1,100',
//            "billing_phone"=>'integer|max:100000000000',
        );
        if(Input::get("id") && Input::get("id") != ''){
            if(Input::get("name") != '') {
                $rules['name'] = 'required|between:1,100';
            }
            if(Input::get("licence_num") != '') {
                $rules['licence_num'] = 'required|between:1,100|unique:maintenance_supplier,licence_num,' . Input::get("id");
            }
        }else{
            if(Input::get("name") != '') {
                $rules['name'] = 'required|between:1,100|unique:maintenance_supplier,name';
            }
            if(Input::get("licence_num") != '') {
                $rules['licence_num'] = 'required|between:1,100|unique:maintenance_supplier,licence_num';
            }
        }
        $validator = Validator::make(Input::all(),$rules);
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                if(array_key_exists('name',$validator->messages()->getMessages())){
                    $ids = MaintenanceSupplier::where('name',Input::get("name"))->select('id')->get();
                    $ids_str = '';
                    foreach($ids as $va){
                        $ids_str .= $va->id . ',';
                    }
                    $ids_str = substr($ids_str,0,strlen($ids_str) - 1);
                    $response["msg"] .= '，已存在供应商名称，请查看供应商id：' . $ids_str;
                }
                if(array_key_exists('licence_num',$validator->messages()->getMessages())){
                    $ids = MaintenanceSupplier::where('licence_num',Input::get("licence_num"))->select('id')->get();
                    $ids_str = '';
                    foreach($ids as $va){
                        $ids_str .= $va->id . ',';
                    }
                    $ids_str = substr($ids_str,0,strlen($ids_str) - 1);
                    $response["msg"] .= '，已存在供应商执照编码，请查看供应商id：' . $ids_str;
                }
                break;
            }
            $token = Input::get("token");
            $name = Input::get("name");
            $licence_num = Input::get("licence_num");
            $industry_type = Input::get("industry_type");
            $operating_address = Input::get("operating_address");
            $address = Input::get("address");
            $scope = Input::get("scope");
            $country = Input::get("country");
            $juridical = Input::get("juridical");
            $contacts = Input::get("contacts");
            $contacts_number = Input::get("contacts_number");
            $fax = Input::get("fax",'');
            $email = Input::get("email",'');
            $postcode = Input::get("postcode",'');
            $other_info = Input::get("other_info",'');
            $gather_bank = Input::get("gather_bank");
            $gather_account = Input::get("gather_account");
            $bank = Input::get("bank");
            $account = Input::get("account");
            $taxpayer = Input::get("taxpayer");
            $billing_phone = Input::get("billing_phone",'');
            $province_id = Input::get('province_id');
            $city_id = Input::get('city_id');
            $region_id = Input::get('region_id');
            
            $res = $this->verificationPMSUserToken($token,$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            if(Input::get("id") && Input::get("id") != ''){
                $ms = MaintenanceSupplier::find(Input::get("id"));
                $old = clone $ms;
                $ms->updated_at = Common::currentTimeString();
                $ms->version += 1;
                $erp_id = $ms->erp_id;
            }else{
                $ms = new MaintenanceSupplier();
                $ms->created_at = Common::currentTimeString();
                $ms->updated_at = Common::currentTimeString();
                $ms->shop_id = 0;
                $ms->created_type = 2;      //创建于哪个平台 1:ERP 2:PMS 3:ARC
                $ms->create_by_name = $res['user']->name;
                $ms->create_by = $res['user']->id;
                $ms->purchase_type = 1;
                $erp_id = "";
            } 
            
            $issetErpSupplier = $this->issetErpSupplier($name,$erp_id);
            if (!$issetErpSupplier) {
                $response = Lang::get("pms_error.pms_supplier_error_40029");
                break;
            }
            $issetErpLicence_num = $this->issetErpLicence_num($licence_num,$erp_id);
            if (!$issetErpLicence_num) {
                $response = Lang::get("pms_error.pms_supplier_error_40030");
                break;
            }
            $ms->name = $name;
            $ms->bm=Pinyin::getShortPinyin($name);
            $ms->licence_num = $licence_num;
            $ms->industry_type = $industry_type;
            $ms->operating_address = $operating_address;
            $ms->address = $address;
            $ms->scope = $scope;
            $ms->country = $country;
            $ms->juridical = $juridical;
            $ms->contacts = $contacts;
            $ms->contacts_number = $contacts_number;
            $ms->fax = $fax;
            $ms->email = $email;
            $ms->postcode = $postcode;
            $ms->other_info = $other_info;
            $ms->gather_bank = $gather_bank;
            $ms->gather_account = $gather_account;
            $ms->bank = $bank;
            $ms->account = $account;
            $ms->taxpayer = $taxpayer;
            $ms->billing_phone = $billing_phone;
            $ms->type = 2;
            $ms->status = 1;
            $ms->province_id = $province_id;
            $ms->created_type = 3;

            $province_info = DataResourceProvinceType::getInfoById($province_id);
            if(!empty($province_info)){
                $ms->province_text = $province_info['name'];
            }
            $ms->city_id = $city_id;
            $city_info = DataResourceCity::getInfoById($city_id);
            if(!empty($city_info)){
                $ms->city_text = $city_info['city_name'];
            }
            $ms->region_id = $region_id;
            $region_info = DataResourceRegion::getInfoById($region_id);
            if(!empty($region_info)){
                $ms->region_text = $region_info['region_name'];
            }
            try {
                $ms->save();
                if(Input::get("id") && Input::get("id") != '') {
                    PmsOpLog::write('supplier', Input::get("id"),'update', '用户:' . $res['user']->id . ',更改供应商：' . Input::get("id"), json_encode($old), json_encode(MaintenanceSupplier::find($ms->id)), $res['user']->id);
                }else{

                    // $url = Config::get('config.kingdee_local_api').'/kingdeescs/create_suppller?token='.sha1(md5('anhuiscs'.date("Y-m-d H",time()))).'&name='.Input::get("name");
                    // $re = Httpful::get($url)
                    //     ->timeoutIn(150)
                    //     ->sendsForm()->send();
                    // $re = json_decode($re->body);
                    // if($re->code!=0){
                    //     Log::error($re->msg);
                    //     $response = Lang::get("scs_error.supplier_update_error_30002");
                    //     break;
                    // }
                    // $ms->kingdee_supper=$re->result->gongyingshang_fu;
                    $erp_supplier_id = $this->insertErpSupplier($ms);
                    $ms->erp_id = $erp_supplier_id;
                    $ms->save();
                    PmsOpLog::write('supplier', $ms->id,'new', '用户:' . $res['user']->id . ',新建供应商：' . Input::get("id"), null, json_encode(MaintenanceSupplier::find($ms->id)), $res['user']->id);
                }
            }catch(Exception $e){
                Log::error("error", array("system" => "pms" ,"event" => "storeOne", 'input' =>Input::all() ,"exception" => $e));
                echo $e->getMessage();
                $response = Lang::get("pms_error.supplier_update_error_30002");
                break;
            }
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "storeOne", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * 经营资料
     */
    //经营资料
    public function getOperationInfo(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "supplier_id"=>'required|integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $ms = MaintenanceSupplier::find(Input::get("supplier_id"));
            if(!$ms){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            $response['result']['supplier_id'] = Input::get("id");
            $response['result']['major_type'] = $ms->major_type;
            $response['result']['major_business'] = $ms->car_type;
            $models = SupplierCarModels::leftJoin('anhui_data.car_brand as csi','supplier_car_models.model_id','=','csi.id')
                ->where('supplier_car_models.supplier_id',Input::get("supplier_id"))->where('supplier_car_models.status',1)
                ->select('supplier_car_models.id as s_model_id','supplier_car_models.model_id','csi.name as model_name')
                ->get();
            $response['result']['models'] = $models;
            $brands = SupplierBrands::leftJoin('supply_brand as cbt','supplier_brands.brand_id','=','cbt.id')
                ->where('supplier_brands.supplier_id',Input::get("supplier_id"))->where('supplier_brands.status',1)
                ->select('supplier_brands.id as s_brand_id','supplier_brands.brand_id','cbt.brand_name')
                ->get();
            $response['result']['brands'] = $brands;
            $response['result']['regular_pay'] = MaintenanceSupplier::$regular_pay;
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "getOperationInfo", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    //可选车型
    public function getOperationModels(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "name"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $name = Input::get("name");
            $models = DataCarBrand::where('name','like','%' . $name . '%')->where('status',1)->select('id as model_id','name as model_name');
            $count = $models->count();
            $models = $models->get();
            $response['result']['name'] = $name;
            $response['result']['count'] = $count;
            $response['result']['models'] = $models;
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "getOperationModels", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    //可选品牌
    public function getOperationBrands(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "name"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $name = Input::get("name");
            $models = SupplyBrand::where('brand_name','like','%' . $name . '%')->where('status',1)->select('id as brand_id','brand_name');
            $count = $models->count();
            $models = $models->get();
            $response['result']['name'] = $name;
            $response['result']['count'] = $count;
            $response['result']['brands'] = $models;
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "getOperationBrands", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    //更改关联车型状态
    public function statusOperationModel(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "supplier_id"=>'required',
                "model_id"=>'required',
                "status"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $supplier = MaintenanceSupplier::find(Input::get("supplier_id"));
            if(!$supplier){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            $model = DataCarBrand::find(Input::get("model_id"));
            if(!$model){
                $response = Lang::get("pms_error.supplier_not_exit_error_30003");
                break;
            }
            $scm = SupplierCarModels::where('supplier_id',Input::get("supplier_id"))->where('model_id',Input::get("model_id"))->first();
            if(!$scm){
                $scm = new SupplierCarModels();
                $scm->supplier_id = Input::get("supplier_id");
                $scm->model_id = Input::get("model_id");
                $scm->created_by = $res['user']->id;
                $scm->created_at = Common::currentTimeString();
                PmsOpLog::write('supplier',Input::get("supplier_id"),'new','用户:' . $res['user']->id . ',新建关联车品牌,新状态：' . Input::get("status"),null,'supplier_id:' . Input::get("supplier_id") . ',model_id:' . Input::get("model_id"),$res['user']->id);
            }else{
                PmsOpLog::write('supplier',Input::get("supplier_id"),'update','用户:' . $res['user']->id . ',更改关联车品牌,新状态：' . Input::get("status"),'supplier_id:' . $scm->supplier_id . ',model_id:' . $scm->model_id,'supplier_id:' . Input::get("supplier_id") . ',model_id:' . Input::get("model_id"),$res['user']->id);
            }
            $scm->status = Input::get("status");
            $scm->updated_by = $res['user']->id;
            $scm->updated_at = Common::currentTimeString();
            try {
                $scm->save();
            }catch(Exception $e){
                Log::error("error", array("system" => "pms" ,"event" => "statusOperationModel", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("pms_error.supplier_update_error_30002");
                break;
            }
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "statusOperationModel", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    //更改关联品牌状态
    public function statusOperationBrand(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "supplier_id"=>'required',
                "brand_id"=>'required',
                "status"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $supplier = MaintenanceSupplier::find(Input::get("supplier_id"));
            if(!$supplier){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            $model = SupplyBrand::find(Input::get("brand_id"));
            if(!$model){
                $response = Lang::get("pms_error.supplier_not_exit_error_30004");
                break;
            }
            $scm = SupplierBrands::where('supplier_id',Input::get("supplier_id"))->where('brand_id',Input::get("brand_id"))->first();
            if(!$scm){
                $scm = new SupplierBrands();
                $scm->supplier_id = Input::get("supplier_id");
                $scm->brand_id = Input::get("brand_id");
                $scm->created_by = $res['user']->id;
                $scm->created_at = Common::currentTimeString();
                PmsOpLog::write('supplier',Input::get("supplier_id"),'new','用户:' . $res['user']->id . ',新建关联耗材品牌,新状态：' . Input::get("status"),null,'supplier_id:' . Input::get("supplier_id") . ',brand_id:' . Input::get("brand_id"),$res['user']->id);
            }else{
                PmsOpLog::write('supplier',Input::get("supplier_id"),'update','用户:' . $res['user']->id . ',更改关联耗材品牌,新状态：' . Input::get("status"),'supplier_id:' . $scm->supplier_id . ',brand_id:' . $scm->brand_id,'supplier_id:' . Input::get("supplier_id") . ',brand_id:' . Input::get("brand_id"),$res['user']->id);
            }
            $scm->status = Input::get("status");
            $scm->updated_by = $res['user']->id;
            $scm->updated_at = Common::currentTimeString();
            try {
                $scm->save();
            }catch(Exception $e){
                Log::error("error", array("system" => "pms" ,"event" => "statusOperationBrand", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("pms_error.supplier_update_error_30002");
                break;
            }
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "statusOperationBrand", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    //设置主营类型
    public function statusOperationMajor(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "supplier_id"=>'required',
                "major_type"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $ms = MaintenanceSupplier::find(Input::get("supplier_id"));
            if(!$ms){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            $old = clone $ms;
            $ms->major_type = Input::get('major_type');
            try {
                $ms->save();
                PmsOpLog::write('supplier',Input::get("supplier_id"),'update','用户:' . $res['user']->id . ',设置主营类型,原类型:' . $old->major_type . ',新类型:' . Input::get('major_type'),json_encode($old),json_encode(MaintenanceSupplier::find(Input::get("supplier_id"))),$res['user']->id);
            }catch(Exception $e){
                Log::error("error", array("system" => "pms" ,"event" => "statusOperationMajor", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("pms_error.supplier_update_error_30002");
                break;
            }
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "statusOperationMajor", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    //设置主营业务
    public function setMajorBusiness(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "supplier_id"=>'required',
//                "car_type"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $ms = MaintenanceSupplier::find(Input::get("supplier_id"));
            if(!$ms){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            $old = clone $ms;
            $ms->car_type = Input::get('car_type','');
            try {
                $ms->save();
                PmsOpLog::write('supplier',Input::get("supplier_id"),'update','用户:' . $res['user']->id . ',设置主营业务,原业务:' . $old->car_type . ',新业务:' . Input::get('car_type'),json_encode($old),json_encode(MaintenanceSupplier::find(Input::get("supplier_id"))),$res['user']->id);
            }catch(Exception $e){
                Log::error("error", array("system" => "pms" ,"event" => "setMajorBusiness", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("pms_error.supplier_update_error_30002");
                break;
            }
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "setMajorBusiness", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * 商品报价
     */
    //列表
    public function getGoodsPrice(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "supplier_id"=>'required|integer',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $ms = MaintenanceSupplier::where(Input::get("supplier_id"));
            if(!$ms){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            $sgps = SupplierGoodsPrice::from('supplier_goods_price as sgp')
//                ->leftJoin('supply_item as si','sgp.goods_id','=','si.id')
                ->where('sgp.supplier_id',Input::get("supplier_id"))->where('sgp.status',1)
//                ->where('sgp.tax_price','!=','0')->where('sgp.tax_price','!=','0.00')->where('sgp.no_tax_price','!=','0')->where('sgp.no_tax_price','!=','0.00')
                ->whereRaw('(((sgp.tax_price != 0.00 and sgp.tax_price != 0) and (sgp.no_tax_price != 0.00 and sgp.no_tax_price != 0)) || ((sgp.tax_price = 0.00 and sgp.tax_price = 0) and (sgp.no_tax_price != 0.00 and sgp.no_tax_price != 0)) || ((sgp.tax_price != 0.00 and sgp.tax_price != 0) and (sgp.no_tax_price = 0.00 and sgp.no_tax_price = 0)))')
//                ->select('sgp.*','si.model as item_name','si.code','si.bz_unit','si.sale_unit','si.pack','si.specification','si.retrieval_code');
                ->select('sgp.*');
            $count = $sgps->count();
            $in_all = Input::all();
            if(isset($in_all['page']) && isset($in_all['page_size'])) {
                $page_size = Input::get("page_size", 25);
                $page = Input::get("page", 1);
                $sgps = $sgps->skip($page_size*($page-1))->take($page_size)->get();
            }else{
                $sgps = $sgps->get();
            }
            foreach($sgps as $key=>&$sg){
                $sg->name = '';
                $sg->commodity_code = '';
                $sg->volume_size = '';
                $sg->code = '';
                $sg->retrieval_code = '';
                $sg->unit = null;
                $sg->saleUnit = null;
                $goods = SupplyItem::find($sg->goods_id);
                if($goods){
                    $sg->name = $goods->name;
                    $sg->commodity_code = $goods->commodity_code;
                    $sg->volume_size = $goods->volume_size;
                    $sg->code = $goods->code;
                    $sg->retrieval_code = $goods->retrieval_code;
                    $unit = DataSupplyUnit::find($goods->unit_id);
                    if($unit){
                        $sg->unit = $unit;
                    }
                    $saleUnit = DataSupplyUnit::find($goods->sale_unit_id);
                    if($saleUnit) {
                        $sg->saleUnit = $saleUnit;
                    }
                }
            }
            $response['result']['supplier_id'] = Input::get("supplier_id");
            $response['result']['count'] = $count;
            $response['result']['goods'] = $sgps;
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "getGoodsPrice", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    //可选商品
    public function getGoods(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "name"=>'required',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $ms = MaintenanceSupplier::where(Input::get("supplier_id"));
            if(!$ms){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            $page_size = Input::get("page_size",25);
            $page = Input::get("page",1);
            $sgps = SupplyItem::with('unit','saleUnit')->where('retrieval_code','like','%' . Input::get("name") . '%')->where('status',1);
            $count = $sgps->count();
            $sgps = $sgps->skip($page_size*($page-1))->take($page_size)->get();
            foreach($sgps as &$sg){
                $sg->f_code = '';
            }
            $response['result']['name'] = Input::get("name");
            $response['result']['count'] = $count;
            $response['result']['goods'] = $sgps;
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "getGoods", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    //获取商品报价
    public function getGoodsPriceOne(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "supplier_id"=>'required|integer',
                "goods_id"=>'required|integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $ms = MaintenanceSupplier::where(Input::get("supplier_id"));
            if(!$ms){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            $good = SupplyItem::where(Input::get("goods_id"));
            if(!$good){
                $response = Lang::get("pms_error.supplier_not_exit_error_30005");
                break;
            }
            $price = SupplierGoodsPrice::where('goods_id',Input::get("goods_id"))->where('supplier_id',Input::get("supplier_id"))->where('status',1)->orderBy('id','desc')->first();
            $tax_price = '';
            $no_tax_price = '';
            if($price){
                $tax_price = $price->tax_price;
                $no_tax_price = $price->no_tax_price;
            }
            $response['result']['supplier_id'] = Input::get("supplier_id");
            $response['result']['goods_id'] = Input::get("goods_id");
            $response['result']['tax_price'] = $tax_price;
            $response['result']['no_tax_price'] = $no_tax_price;
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "getGoodsPriceOne", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    //保存商品报价
    public function storeGoodsPrice(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "supplier_id"=>'required|integer',
                "goods_id"=>'required|integer',
                "tax_price"=>'required',
                "no_tax_price"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $ms = MaintenanceSupplier::where(Input::get("supplier_id"));
            if(!$ms){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            $good = SupplyItem::where(Input::get("goods_id"));
            if(!$good){
                $response = Lang::get("pms_error.supplier_not_exit_error_30005");
                break;
            }
            $price = SupplierGoodsPrice::where('goods_id',Input::get("goods_id"))->where('supplier_id',Input::get("supplier_id"))->where('status',1)->orderBy('id','desc')->first();
            try {
                if($price){
                    $old = clone $price;
                    PmsOpLog::write('supplier',Input::get("supplier_id"),'update','用户:' . $res['user']->id . ',更改商品报价','supplier_id:' . $old->supplier_id . ',goods_id:' . $old->goods_id . ',tax_price:' . $old->tax_price . ',no_tax_price:' . $old->no_tax_price,'supplier_id:' . Input::get("supplier_id") . ',goods_id:' . Input::get("goods_id") . ',tax_price:' . Input::get("tax_price") . ',no_tax_price:' . Input::get("no_tax_price"),$res['user']->id);
                    SupplierGoodsPrice::where('id',$price->id)->update(['tax_price'=>Input::get("tax_price"),'no_tax_price'=>Input::get("no_tax_price"),'updated_at'=>Common::currentTimeString(),'updated_by'=>$res['user']->id]);
                }else{
                    $new_price = new SupplierGoodsPrice();
                    $new_price->supplier_id = Input::get("supplier_id");
                    $new_price->goods_id = Input::get("goods_id");
                    $new_price->tax_price = Input::get("tax_price");
                    $new_price->no_tax_price = Input::get("no_tax_price");
                    $new_price->status = 1;
                    $new_price->created_at = Common::currentTimeString();
                    $new_price->created_by = $res['user']->id;
                    $new_price->save();
                    PmsOpLog::write('supplier',Input::get("supplier_id"),'new','用户:' . $res['user']->id . ',新建商品报价',null,'supplier_id:' . Input::get("supplier_id") . ',goods_id:' . Input::get("goods_id") . ',tax_price:' . Input::get("tax_price") . ',no_tax_price:' . Input::get("no_tax_price"),$res['user']->id);
                }
            }catch(Exception $e){
                Log::error("error", array("system" => "pms" ,"event" => "storeGoodsPrice", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("pms_error.supplier_update_error_30002");
                break;
            }
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "storeGoodsPrice", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    //导入商品报价
    public function importGoodsPrice(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "supplier_id"=>'required|integer',
                "data"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $ms = MaintenanceSupplier::where(Input::get("supplier_id"));
            if(!$ms){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            if(Input::get('data') == '' || is_null(Input::get('data'))){
                $response = Lang::get("pms_error.supplier_price_error_30009");
                break;
            }
            $supplier_id = Input::get('supplier_id');
            $data = Input::get('data');
            $data = json_decode($data);
            if(!is_array($data)){
                $response = Lang::get("pms_error.supplier_price_error_31001");
                break;
            }
            Log::debug($data);
//            $ra = 1;
            foreach($data as $da){
                Log::debug($da->goods_id);
                if(!isset($da->goods_id) || $da->goods_id == '' || is_null($da->goods_id)){
                    $ra = 0;
                    break;
                }
                $good = SupplyItem::find($da->goods_id);
                if($good) {
//                    $ra = 0;
//                    break;
//                }
                    $price = SupplierGoodsPrice::where('goods_id', $da->goods_id)->where('supplier_id', $supplier_id)->where('status', 1)->orderBy('id', 'desc')->first();
                    if (!$price) {
                        $price = new SupplierGoodsPrice();
                        $price->supplier_id = $supplier_id;
                        $price->created_at = Common::currentTimeString();
                        $price->created_by = $res['user']->id;
                        $price->status = 1;
                        PmsOpLog::write('supplier', Input::get("supplier_id"), 'new', '用户:' . $res['user']->id . ',导入并新建商品报价', null,
                            'supplier_id:' . $supplier_id . ',goods_id:' . $da->goods_id . ',tax_price:' . $da->tax_price . ',no_tax_price:' . $da->no_tax_price, $res['user']->id);
                    } else {
                        $old = clone $price;
                        $price->updated_at = Common::currentTimeString();
                        $price->updated_by = $res['user']->id;
                        PmsOpLog::write('supplier', Input::get("supplier_id"), 'update', '用户:' . $res['user']->id . ',导入并更改商品报价', 'supplier_id:' . $supplier_id . ',goods_id:' . $old->goods_id . ',tax_price:' . $old->tax_price . ',no_tax_price:' . $old->no_tax_price,
                            'supplier_id:' . $supplier_id . ',goods_id:' . $da->goods_id . ',tax_price:' . $da->tax_price . ',no_tax_price:' . $da->no_tax_price, $res['user']->id);
                    }
                    $price->goods_id = $da->goods_id;
                    $price->tax_price = $da->tax_price;
                    $price->no_tax_price = $da->no_tax_price;
                    $price->save();
                }
            }
//            if($ra == 0){
//                $response = Lang::get("pms_error.supplier_price_error_31002");
//                break;
//            }
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "importGoodsPrice", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    //操作记录
    public function getOPRecords(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "supplier_id"=>'required|integer',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $ms = MaintenanceSupplier::find(Input::get("supplier_id"));
            if(!$ms){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            $page_size = Input::get("page_size",25);
            $page = Input::get("page",1);
            $skip = $page_size*($page-1);
            $supplier_id = Input::get("supplier_id");
            
            $sql_1 = "select *  from anhui.pms_op_log  where model='supplier' and supplier_id=".$supplier_id;            
            $sql_2 = "select op.* from anhui_data.op_log as op where op.model='supplier' and op.supplier_id=".$ms->erp_id;
            $sql = "select * from ( $sql_1 UNION ALL $sql_2) a order by created_at desc limit $skip,$page_size";
            $count_sql = "select count(*) as count from ( $sql_1 UNION ALL $sql_2) a";
            $count = DB::select($count_sql);
            $sgps = DB::select($sql);
            
//            $sgps = PmsOpLog::where('supplier_id',Input::get('supplier_id'))->orderBy('id','desc');
//            $count = $sgps->count();
//            $sgps = $sgps->skip($page_size*($page-1))->take($page_size)->get();
            foreach($sgps as &$sg){
                $sg->created_by_name = '';
                if ($sg->created_type == 1) { //erp
                    $pu = DB::connection('mysql_data')->table("system_users")->where("id",$sg->created_by)->first();
                    if($pu)$sg->created_by_name = $pu->name;
                }else{
                    $pu = PMSUser::find($sg->created_by);
                    if($pu)$sg->created_by_name = $pu->real_name;
                }

            }
            
            $response['result']['created_types'] = MaintenanceSupplier::$created_types;
            $response['result']['supplier_id'] = Input::get("supplier_id");
            $response['result']['count'] = $count[0]->count;
            $response['result']['lists'] = $sgps;
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "getOPRecords", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * 附件
     */
    //列表
    public function fileList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "supplier_id"=>'required|integer',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $ms = MaintenanceSupplier::find(Input::get("supplier_id"));
            if(!$ms){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }

            $page_size = Input::get("page_size",25);
            $page = Input::get("page",1);
            $types = PMSFiles::$file_types;
            $skip = $page_size*($page-1);
            $supplier_id = Input::get("supplier_id");
            
            $sql_1 = "select pf.*  from anhui.pms_files as pf where pf.status=1 and supplier_id=".$supplier_id;            
            $sql_2 = "select uf.* from anhui_data.upload_files as uf where uf.status=1 and uf.supplier_id=".$ms->erp_id;
            $sql = "select * from ( $sql_1 UNION ALL $sql_2) a order by created_at desc limit $skip,$page_size";
            $count_sql = "select count(*) as count from ( $sql_1 UNION ALL $sql_2) a";
            $count = DB::select($count_sql);
            $files = DB::select($sql);
//            $files = PMSFiles::where('supplier_id',Input::get("supplier_id"))->where('status',1);
//            $count = $files->count();
//            $files = $files->skip($page_size*($page-1))->take($page_size)->get();
//            $file_url = 'http://'.$_SERVER['SERVER_NAME'].'/app/pms/file/';
//            $img_url = 'http://'.$_SERVER['SERVER_NAME'].'/app/pms/img/';
            $pms_file_url = Config::get('config.pms_file_url');
                $pms_img_url = Config::get('config.pms_img_url');
                $erp_file_url = Config::get('config.erp_file_url');
                $erp_img_url = Config::get('config.erp_img_url');
            foreach($files as $fi){
                $fi->created_by_name = "";
                if ($fi->created_type == 1) { //ERP
                    $cr = DB::connection('mysql_data')->table("system_users")->where("id",$fi->created_by)->first();
                    if($cr)$fi->created_by_name = $cr->name;
                    if($fi->type == 1){
                        $fi->file = $erp_file_url . $fi->file;
                    }elseif($fi->type == 2){
                        $fi->img = $erp_img_url . $fi->img;
                    }
                }else{
                    $cr = PMSUser::find($fi->created_by);
                    if($cr)$fi->created_by_name = $cr->real_name;
                    if($fi->type == 1){
                        $fi->file = $pms_file_url . $fi->file;
                    }elseif($fi->type == 2){
                        $fi->img = $pms_img_url . $fi->img;
                    }
                }
                $fi->type_name = $types[$fi->type];
            }
            
            $response['result']['created_types'] = MaintenanceSupplier::$created_types;
            $response['result']['supplier_id'] = Input::get("supplier_id");
            $response['result']['count'] = $count[0]->count;
            $response['result']['files'] = $files;
            $response['extra']['file_types'] = $types;
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "fileList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    //上传
    public function uploadFile(){
        header('Access-Control-Allow-Origin:*');
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "supplier_id"=>'required|integer',
                'name' => 'required',
                'type' => 'required',
                'file'=> 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $type = Input::get('type');
            $icon_file = Input::file('file');
            $ex = $icon_file->getClientOriginalExtension();
            if($type == 2 && !in_array($ex,PMSFiles::$img_ext)){
                $response = Lang::get("pms_error.supplier_img_error_30006");
                break;
            }
            $ms = MaintenanceSupplier::find(Input::get("supplier_id"));
            if(!$ms){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            $name = $icon_file->getClientOriginalName();
            if($type == 1){
                $icon_file->move(Config::get('config.pms_file'),$name);
            }elseif($type == 2){
                $icon_file->move(Config::get('config.pms_img'),$name);
            }
            $file = new PMSFiles();
            $file->supplier_id = Input::get('supplier_id');
            $file->status = 1;
            $file->name = Input::get('name');
            $file->type = $type;
            $file->file_type = Input::get('file_type');
            $file->created_type = 2;
            if($type == 1) {
                $file->file = $name;
            }elseif($type == 2){
                $file->img = $name;
            }
            $file->created_by = $res['user']->id;
            try {
                $file->save();
                PmsOpLog::write('supplier',Input::get("supplier_id"),'new','用户:' . $res['user']->id . ',上传文件',null,json_encode(PMSFiles::find($file->id)),$res['user']->id);
            }catch(Exception $e){
                Log::error("error", array("system" => "pms" ,"event" => "uploadFile", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("pms_error.supplier_update_error_30002");
                break;
            }
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "uploadFile", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * 系统配置
     */
    //列表
    public function getAccountSys(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "supplier_id"=>'required|integer',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $ms = MaintenanceSupplier::where(Input::get("supplier_id"));
            if(!$ms){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            $page_size = Input::get("page_size",25);
            $page = Input::get("page",1);
            $sgps = SupplierAccounts::where('supplier_id',Input::get('supplier_id'))->orderBy('id','desc');
            $count = $sgps->count();
            $sgps = $sgps->skip($page_size*($page-1))->take($page_size)->get();
            $response['result']['supplier_id'] = Input::get("supplier_id");
            $response['result']['count'] = $count;
            $response['result']['lists'] = $sgps;
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "getAccountSys", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    //账套列表
    public function getAccountList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "supplier_id"=>'required|integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $ms = MaintenanceSupplier::where(Input::get("supplier_id"));
            if(!$ms){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            $response['result']['supplier_id'] = Input::get("supplier_id");
            $list = JinDie::getDataQuery();
            $result = null;
            $sgps = SupplierAccounts::where('supplier_id',Input::get('supplier_id'))->select('book_code')->distinct()->get()->toArray();
            $sgps = array_column($sgps,'book_code');
            if($list && !is_null($list) && $list != 'null'){
                $result = json_decode($list);
                foreach($result as $key=>$val) {
                    if(in_array($val->FAccountBookCode,$sgps)){
                        unset($result[$key]);
                    }
                }
            }
            $response['result']['lists'] = $result;
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "getAccountList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    //改状态
    public function statusAccount(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "supplier_id"=>'required|integer',
                "account_id"=>'required|integer',
                "status"=>'required|integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $ms = MaintenanceSupplier::where(Input::get("supplier_id"));
            if(!$ms){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            $sa = SupplierAccounts::find(Input::get('account_id'));
            if(!$sa){
                $response = Lang::get("pms_error.supplier_account_error_30007");
                break;
            }
            $old = clone $sa;
            $sa->status = Input::get('status');
            try{
                $sa->save();
                PmsOpLog::write('supplier',Input::get("supplier_id"),'update','用户:' . $res['user']->id . ',更改账套关系状态,原状态:' . $old->status . ',新状态:' . Input::get("status"),json_encode($old),json_encode(SupplierAccounts::find(Input::get('account_id'))),$res['user']->id);
                break;
            }catch (Exception $e) {
                Log::error("error", array("system" => "pms" ,"event" => "statusAccount", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("pms_error.supplier_update_error_30002");
                break;
            }
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "statusAccount", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    //保存账套关系
    public function storeAccount(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "supplier_id"=>'required|integer',
                "book_code"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $ms = MaintenanceSupplier::where(Input::get("supplier_id"));
            if(!$ms){
                $response = Lang::get("pms_error.supplier_not_exit_error_30001");
                break;
            }
            $book_name = '';
            $list = JinDie::getDataQuery();
            if($list && !is_null($list) && $list != 'null') {
                $result = json_decode($list);
                foreach($result as $res1){
                    if($res1->FAccountBookCode == Input::get("book_code")){
                        $book_name = $res1->FAccountBookName;
                        break;
                    }
                }
            }
            if($book_name == ''){
                $response = Lang::get("pms_error.supplier_book_error_30008");
                break;
            }
            try {
                $new_price = new SupplierAccounts();
                $new_price->book_code = Input::get("book_code");
                $new_price->supplier_id = Input::get("supplier_id");
                $new_price->book_name = $book_name;
                $new_price->status = 1;
                $new_price->class_id = '008';
                $new_price->class_name = '供应商';
                $new_price->created_at = Common::currentTimeString();
                $new_price->created_by = $res['user']->id;
                $new_price->save();
                PmsOpLog::write('supplier',Input::get("supplier_id"),'new','用户:' . $res['user']->id . ',新建账套关系',null,json_encode(SupplierAccounts::find($new_price->id)),$res['user']->id);
            }catch(Exception $e){
                Log::error("error", array("system" => "pms" ,"event" => "storeGoodsPrice", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("pms_error.supplier_update_error_30002");
                break;
            }
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "storeGoodsPrice", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    //保存账套关系
    public function editRegularPay(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "supplier_id"=>'required|integer',
                "regular_pay"=>'required', //'1'=>'定期结算','0'=>'现金结算'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $ms = MaintenanceSupplier::find(Input::get("supplier_id"));
            $ms ->regular_pay = Input::get("regular_pay");
            if (!$ms->save()) {
                $response = Lang::get("pms_error.supplier_update_error_30002");
            }
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "editRegularPay", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-4-17 下午2:30
     * @Description:     获取省份
     * @param string $token     用户token
     * @param string $name      省份名称 [模糊查询]
     * @link http://api.anhui.com/v1/pms/supplier/get_province?token=2a3baa6fbedc7e7716bfad375f6d477f
     */
    public function get_province() {
        $validator = Validator::make(Input::all(), [
            'token' => 'required',
        ]);
        $response = [
            'code' => 0,
            'msg' => 'ok',
        ];
        
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $name = Input::get('name', '');
            
            $list = DataResourceProvinceType::select('id', 'name', 'short_name')
                    ->where('status', 1);
            if(!empty($name)){
                $list = $list->where('name', 'like', '%'.$name.'%');
            }
            $list = $list->orderBy('id', 'ASC')->get();
            
            $response['result'] = $list;
        } while (FALSE);
        
        Log::info('info', ['system' => 'pms', 'event' => 'supplier/get_province', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-4-17 下午3:35
     * @Description:     获取市
     * @param string $token     用户token
     * @param int $province_id  省id
     * @param string $name      市名称 [模糊查询]
     * @param int $num          一次展示的数量 [ 默认为50 ]
     * @link http://api.anhui.com/v1/pms/supplier/get_city?token=2a3baa6fbedc7e7716bfad375f6d477f
     */
    public function get_city() {
        $validator = Validator::make(Input::all(), [
            'token' => 'required',
        ]);
        $response = [
            'code' => 0,
            'msg' => 'ok',
        ];
        
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $province_id = Input::get('province_id', '');
            $name = Input::get('name', '');
            $num = Input::get('num', 50);
            
            $list = DataResourceCity::select('id', 'city_name', 'province_id');
            if(!empty($province_id)){
                $list = $list->where('province_id', '=', $province_id);
            }
            if(!empty($name)){
                $list = $list->where('city_name', 'like', '%'.$name.'%');
            }
            $list = $list->skip(0)->take($num)
                    ->orderBy('id', 'ASC')
                    ->get();
            
            $response['result'] = $list;
        } while (FALSE);
        
        Log::info('info', ['system' => 'pms', 'event' => 'supplier/get_city', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-4-17 下午3:55
     * @Description:     获取区县
     * @param string $token     用户token
     * @param int $city_id      市id
     * @param string $name      区县名称 [模糊查询]
     * @param int $num          一次展示的数量 [ 默认为50 ]
     * @link http://api.anhui.com/v1/pms/supplier/get_region?token=2a3baa6fbedc7e7716bfad375f6d477f
     */
    public function get_region() {
        $validator = Validator::make(Input::all(), [
            'token' => 'required',
        ]);
        $response = [
            'code' => 0,
            'msg' => 'ok',
        ];
        
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $city_id = Input::get('city_id', '');
            $name = Input::get('name', '');
            $num = Input::get('num', 50);
            
            $list = DataResourceRegion::select('id', 'region_name', 'city_id');
            if(!empty($city_id)){
                $list = $list->where('city_id', '=', $city_id);
            }
            if(!empty($name)){
                $list = $list->where('region_name', 'like', '%'.$name.'%');
            }
            $list = $list->skip(0)->take($num)
                    ->orderBy('id', 'ASC')
                    ->get();
            
            $response['result'] = $list;
        } while (FALSE);
        
        Log::info('info', ['system' => 'pms', 'event' => 'supplier/get_region', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * @Author:          zk
     * @DateTime:        18-4-18 下午2:00
     * @Description:     获取所有的省市区县
     * @param string $token     用户token
     * @link http://api.anhui.com/v1/pms/supplier/get_province_city_region?token=dd8e24c8fea7096386088f2813768597
     */
    public function get_province_city_region() {
        $validator = Validator::make(Input::all(), [
            'token' => 'required',
        ]);
        $response = [
            'code' => 0,
            'msg' => 'ok',
        ];
        
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $res_list = [];
            $province_list = DataResourceProvinceType::select('id', 'name', 'short_name')
                    ->where('status', 1)
                    ->orderBy('id', 'ASC')
                    ->get()
                    ->toArray();
            $city_list = DataResourceCity::select('id', 'city_name', 'province_id')
                    ->orderBy('id', 'ASC')
                    ->get()
                    ->toArray();
            $region_list = DataResourceRegion::select('id', 'region_name', 'city_id')
                    ->orderBy('id', 'ASC')
                    ->get()
                    ->toArray();
            if(!empty($province_list)){
                if(!empty($city_list)){
                    $city_type = TRUE;
                } else {
                    $city_type = FALSE;
                }
                if(!empty($region_list)){
                    $region_type = TRUE;
                } else {
                    $region_type = FALSE;
                }
                $tag_p = 0;
                foreach ($province_list as $province) {
                    $res_list[$tag_p] = $province;
                    if($city_type){
                        $tag_c = 0;
                        foreach ($city_list as $k_c => $city) {
                            if($city['province_id'] == $province['id']){
                                $res_list[$tag_p]['citys'][$tag_c] = $city;
                                if($region_type){
                                    foreach ($region_list as $k_r => $region) {
                                        if($region['city_id'] == $city['id']){
                                            $res_list[$tag_p]['citys'][$tag_c]['regions'][] = $region;
                                            unset($region_list[$k_r]);
                                        }
                                    }
                                }
                                unset($city_list[$k_c]);
                                $tag_c++;
                            }
                        }
                    }
                    $tag_p++;
                }
            }
            
            $response['result'] = $res_list;
        } while (FALSE);
        
        Log::info('info', ['system' => 'pms', 'event' => 'supplier/get_province_city_region', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
        
        /*
        //耗时稍微长一些
        $validator = Validator::make(Input::all(), [
            'token' => 'required',
        ]);
        $response = [
            'code' => 0,
            'msg' => 'ok',
        ];
        
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $res_list = [];
            $province_list = DataResourceProvinceType::select('id', 'name', 'short_name')
                    ->where('status', 1)
                    ->orderBy('id', 'ASC')
                    ->get();
            
            if(!empty($province_list)){
                $tag_p = 0;
                foreach ($province_list as $province) {
                    $res_list[$tag_p] = [
                        'id' => $province->id,
                        'name' => $province->name,
                        'short_name' => $province->short_name,
                    ];
                    $city_list = DataResourceCity::select('id', 'city_name', 'province_id')
                            ->where('province_id', '=', $province->id)
                            ->orderBy('id', 'ASC')
                            ->get();
                    if(!empty($city_list)){
                        $tag_c = 0;
                        foreach ($city_list as $city) {
                            $res_list[$tag_p]['item'][$tag_c] = [
                                'id' => $city->id,
                                'city_name' => $city->city_name,
                                'province_id' => $city->province_id,
                            ];
                            $region_list = DataResourceRegion::select('id', 'region_name', 'city_id')
                                    ->where('city_id', '=', $city->id)
                                    ->orderBy('id', 'ASC')
                                    ->get();
                            if($region_list){
                                foreach ($region_list as $region) {
                                    $res_list[$tag_p]['item'][$tag_c]['item'][] = [
                                        'id' => $region->id,
                                        'region_name' => $region->region_name,
                                        'city_id' => $region->city_id,
                                    ];    
                                }
                            }
                            $tag_c++;
                        }
                    }
                    $tag_p++;
                }
            }
            $response['result'] = $res_list;
        } while (FALSE);
        
        Log::info('info', ['system' => 'pms', 'event' => 'supplier/get_province_city_region', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
        */
    }
    
        //同步到pms  anhui库
    private function insertErpSupplier($ms) {
            $ms_array = $ms->toArray();
            $ms_array['regular_pay'] = 1;    //同步到ERP平台 统一为 是定期结算  18-9-17 上午11:06
            unset($ms_array['erp_purchase_status']);
            unset($ms_array['erp_id']);
            unset($ms_array['id']);
            unset($ms_array['supplier_class_level']);
            unset($ms_array['tax']);
            unset($ms_array['logistics_freight']);
            
            $erp_supplier = DB::connection('mysql_data')->table("maintenance_supplier")->insertGetId($ms_array);
            return $erp_supplier;
    }
    //验证erp是否存在同名企业
    private function issetErpSupplier($name,$erp_id) {
        if (empty($erp_id)){
            $erp_supplier = DB::connection('mysql_data')->table("maintenance_supplier")->where("name",$name)->first();
        }else{
            $erp_supplier = DB::connection('mysql_data')->table("maintenance_supplier")->where("name",$name)->where("id","<>",$erp_id)->first();
        }

            if ($erp_supplier) { //如果存在同名
                return false;
            }else{
                return true;
            }
    }
    //验证erp是否存在相同营业执照编码企业
    private function issetErpLicence_num($licence_num,$erp_id){
        if (empty($erp_id)){
            $erp_supplier = DB::connection('mysql_data')->table("maintenance_supplier")->where("licence_num",$licence_num)->first();
        }else{ //如果是修改存在erp_id，验证排除自己
            $erp_supplier = DB::connection('mysql_data')->table("maintenance_supplier")->where("licence_num",$licence_num)->where("id","<>",$erp_id)->first();
        }
            if ($erp_supplier) { //如果存在同名
                return false;
            }else{
                return true;
            }
    }

    /**
     * 验证ERP是否有统一社会代码
     */
    private function issetErpCreditNum($licence_credit_num,$erp_id) {
        if (empty($erp_id)){
            $erp_supplier = DB::connection('mysql_data')->table("maintenance_supplier")->where("licence_credit_num",$licence_credit_num)->first();
        }else{ //如果是修改存在erp_id，验证排除自己
            $erp_supplier = DB::connection('mysql_data')->table("maintenance_supplier")->where("licence_credit_num",$licence_credit_num)->where("id","<>",$erp_id)->first();
        }
        if ($erp_supplier) { //如果存在同名
            return false;
        }else{
            return true;
        }
    }
    
    /**
     * 新建供应商基础信息
     * @link http://api.anhui.com/v1/pms/supplier/createSupplier?token=3f0641ce3dc3ebb51ef49973fd5e1dd7
     */
    function createSupplier(){
        $validator = Validator::make(Input::all(), [
            'token' => 'required',
            'name' => 'required',
            'juridical' => 'required',
            'operating_address' => 'required',
            'work_together_type' => 'required',
            'supplier_class_level' => 'required',
        ]);
        $response = [
            'code' => 0,
            'msg' => 'ok',
        ];
        
        do{
            $response = array('code' => 0, 'msg' => 'ok');
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $id = Input::get("id");
            $supplier_class_level = Input::get('supplier_class_level');     //供应商分类等级
            
            //验证当前是否有相同的企业名称
            $name = Input::get("name");
            $supplier = MaintenanceSupplier::where("name",$name)->where("status",1);
            if (!empty($id)) $supplier->where('id',"<>",$id);
            $supplier = $supplier->first();
            if ($supplier){
                $response = Lang::get("pms_error.pms_supplier_error_40031");
                break;
            }
            //验证当前是否有相同的社会统一代码
            $licence_credit_num = Input::get('licence_credit_num');
            if ($licence_credit_num != "") {
                $supplier = MaintenanceSupplier::where("licence_credit_num",$licence_credit_num)->where("status",1);
                if (!empty($id)) $supplier->where('id',"<>",$id);
                $supplier = $supplier->first();
                if ($supplier){
                    $response = Lang::get("pms_error.pms_supplier_error_40033");
                    break;
                }
            }

            if (Input::get("id") && Input::get("id") != ''){
                $ms = MaintenanceSupplier::find(Input::get("id"));
                $old = clone $ms;
                $ms->updated_at = Common::currentTimeString();
                $ms->version += 1;
                $erp_id = $ms->erp_id;
            }else{
                $ms = new MaintenanceSupplier();
                $ms->created_at = Common::currentTimeString();
                $ms->updated_at = Common::currentTimeString();
                $ms->shop_id = 0;
                $ms->created_type = 2;      //创建于哪个平台 1:ERP 2:PMS 3:ARC
                $ms->create_by_name = $res['user']->name;
                $ms->create_by = $res['user']->id;
                $ms->purchase_type = 1;
                $ms->status = 1;
                $erp_id = "";
            }

            
            //验证ERP是否有相同的企业名称
            $issetErpSupplier = $this->issetErpSupplier($name,$erp_id);
            if (!$issetErpSupplier) {
                $response = Lang::get("pms_error.pms_supplier_error_40029");
                break;
            }
            //验证ERP是否有相同的社会统一代码
            if ($licence_credit_num != ""){
                $issetErpCreditNum = $this->issetErpCreditNum($licence_credit_num,$erp_id);
                if (!$issetErpCreditNum) {
                    $response = Lang::get("pms_error.pms_supplier_error_40034");
                    break;
                }
            }

            //基础信息部分
            $ms->name = $name; //公司名称
            $ms->bm = Pinyin::getShortPinyin($name);
            $ms->juridical = Input::get('juridical'); //法定代表人
            $ms->certify_type = Input::get('certify_type')?:null; //证件类型 1身份证  2护照
            $ms->certify_num = Input::get('certify_num')?:null; //证件号码
            $ms->agent = Input::get('agent'); //委托代理人
            $ms->postcode = Input::get('postcode'); //邮编
            $ms->operating_address = Input::get('operating_address'); //营业地址
            $ms->work_together_type = Input::get('work_together_type'); //合作状态 1正常合作  2暂停合作  3终止合作
            $ms->supplier_class_level = $supplier_class_level;  //供应商分类等级(1:全国级;2:区域级;3:门店级;)
            if(Input::get('work_together_type') == 1){
                $ms->purchase_status = 1;   //采购状态 [0:关闭;1:开启;]
            }else{
                $ms->purchase_status = 0;
            }
            $ms->car_type = Input::get('car_type');//主营业务
            //营业执照部分
            $ms->licence_name = Input::get('licence_name');//营业执照公司名称
            $ms->licence_credit_num = Input::get('licence_credit_num');//营业执照社会统一信用代码
            $ms->licence_company_type = Input::get('licence_company_type')?:null;//营业执照中的企业类型1有限责任公司2股份有限公司3个人独资4合伙企业
            $ms->licence_juridical = Input::get('licence_juridical');//营业执照法人代表
            $ms->licence_created_time = Input::get('licence_created_time')?:null;//营业执照成立日期
            $ms->licence_home = Input::get('licence_home');//营业执照住所
            $ms->licence_capital = Input::get('licence_capital');//注册资本
            $ms->licence_term_type = Input::get('licence_term_type')?:null;//营业期限类型1短期2长期
            if(Input::get('licence_term_starttime')){
                $ms->licence_term_starttime = Input::get('licence_term_starttime','');//营业期限开始时间
            }
            if(Input::get('licence_term_endtime','')) {
                $ms->licence_term_endtime = Input::get('licence_term_endtime');//营业期限结束时间
            }
            
            $ms->scope = Input::get('scope');//经营范围
            
           try {
                if(Input::get("id") && Input::get("id") != '') {
                    $ms->save();
                    $erp_supplier_id = $this->updateErpSupplier($ms);
                    PmsOpLog::write('supplier', Input::get("id"),'update', '用户:' . $res['user']->id . ',更改供应商：' . Input::get("id"), json_encode($old), json_encode(MaintenanceSupplier::find($ms->id)), $res['user']->id);
                }else{
                    $erp_supplier_id = $this->insertErpSupplier($ms);
                    $ms->erp_id = $erp_supplier_id;
                    $ms->save();
                    PmsOpLog::write('supplier', $ms->id,'new', '用户:' . $res['user']->id . ',新建供应商：' . Input::get("id"), null, json_encode(MaintenanceSupplier::find($ms->id)), $res['user']->id);
                }
            }catch(Exception $e){
                Log::error("error", array("system" => "pms" ,"event" => "storeOne", 'input' =>Input::all() ,"exception" => $e));
                echo $e->getMessage();
                $response = Lang::get("pms_error.supplier_update_error_30002");
                break;
            }
            $response['result'] = $ms->id;
        } while (FALSE);
        
        Log::info('info', ['system' => 'pms', 'event' => 'supplier/createSupplier', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * 新建供应商业务信息
     * @param int       $logistics_freight      物流运费(1:含运费;2:不含运费;3:按区域设置;4:按门店设置;)
     * @param string    $logistics_freight_ext  物流运费扩展信息
     * [{"id":1,"value":1},{"id":2,"value":2}]
     *  $test = [
            [
                'id' => 1,      //城市或者门店ID
                'value' => 1,   //1:含运费;2:不含运费;
            ],
            [
                'id' => 2,      //城市或者门店ID
                'value' => 2,   //1:含运费;2:不含运费;
            ],
        ];
     * @link http://api.anhui.com/v1/pms/supplier/creatSupplierBusiness?token=3f0641ce3dc3ebb51ef49973fd5e1dd7
     * @link http://api.anhui.com/v1/pms/supplier/creatSupplierBusiness?token=3f0641ce3dc3ebb51ef49973fd5e1dd7&id=1&business_type=2&logistics_freight=4&logistics_freight_ext=[{"id":1,"value":1},{"id":2,"value":2}]
     */
    public function creatSupplierBusiness(){
        $validator = Validator::make(Input::all(), [
            'token' => 'required',
            'id' => 'required',
            'business_type' => 'required',
            //'businss_express' => 'required',
            'logistics_freight' => 'required',
            //logistics_freight 物流运费 值为 3:按区域设置;4:按门店设置; 时，物流运费的扩展信息不能为空
            'logistics_freight_ext' => 'required_if:logistics_freight,3|required_if:logistics_freight,4',
        ]);
        $response = [
            'code' => 0,
            'msg' => 'ok',
        ];
        
        do{
            $response = array('code' => 0, 'msg' => 'ok');
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $id = Input::get("id");
            $logistics_freight = Input::get('logistics_freight');   //物流运费(1:含运费;2:不含运费;3:按区域设置;4:按门店设置;)
            $logistics_freight_ext = Input::get('logistics_freight_ext', '');   //物流运费扩展信息
            $logistics_freight_ext_arr = [];    //物流运费扩展信息数组
            if($logistics_freight_ext != ''){
                $logistics_freight_ext_arr = json_decode($logistics_freight_ext, TRUE);
                if(is_array($logistics_freight_ext_arr)){
                    foreach ($logistics_freight_ext_arr as $v) {
                        if(!in_array($v['value'], [1, 2])){
                            $response = Lang::get("pms_error.supplier_info_error_30025");
                            break 2;
                        }
                    }
                } else {
                    $response = Lang::get("pms_error.supplier_info_error_30024");
                    break;
                }
            }
            if(in_array($logistics_freight, [3, 4])){
                if(empty($logistics_freight_ext_arr)){
                    $response = Lang::get("pms_error.args_error_100000");
                    break;
                }
            }
            
            $ms = MaintenanceSupplier::find($id);
            if (is_null($ms)){
                $response = Lang::get("pms_error.pms_supplier_error_40032");
                break;
            }
            
            $old = clone $ms;
            $ms->updated_at = Common::currentTimeString();
            $ms->version += 1;
            
            //业务信息
            $ms->business_type = Input::get("business_type");//业务信息合作方式1铺货2批量采购3临时采购4其他
            $ms->business_type_comment = Input::get("business_type_comment");//合作方式为"其他“时候。合作方式名
            $ms->business_rebate_policy = Input::get("business_rebate_policy");//返利政策
            //$ms->businss_express = Input::get("businss_express");//物流信息1安惠配送2供应商配送3第三方物流
            $ms->logistics_freight = $logistics_freight;        //物流运费(1:含运费;2:不含运费;3:按区域设置;4:按门店设置;)
            $ms->business_activity = Input::get("business_activity");//市场活动策划
            $ms->business_train = Input::get("business_train");//培训支持
            $ms->after_sale = Input::get("after_sale");//售后质保
            
            try {
                DB::beginTransaction();
                
                $res_ms = $ms->save();
                if(!$res_ms){
                    DB::rollback();
                    $response = Lang::get("pms_error.supplier_update_error_30002");
                    break;
                }
                //物流运费(1:含运费;2:不含运费;3:按区域设置;4:按门店设置;)
                if($logistics_freight == 3){
                    //删除原有信息
                    $area_list = MaintenanceSupplierLogisticsFreightArea::getAreaList($id);
                    if(!empty($area_list)){
                        $res_area_del = MaintenanceSupplierLogisticsFreightArea::where('supplier_id', $id)->delete();
                        if(!$res_area_del){
                            DB::rollback();
                            $response = Lang::get("pms_error.supplier_info_error_30014");
                            break;
                        }
                    }
                    //添加新的区域配置信息
                    $area_data = [];
                    foreach ($logistics_freight_ext_arr as $v) {
                        $temp = [
                            'supplier_id' => $id,
                            'city_id' => $v['id'],
                            'logistics_freight' => $v['value'],
                            'created_at' => Common::num2DateTime(time()),
                            'created_by' => $res['user']->id,
                        ];
                        $area_data[] = $temp;
                    }
                    $res_area_insert = MaintenanceSupplierLogisticsFreightArea::insert($area_data);
                    if(!$res_area_insert){
                        DB::rollback();
                        $response = Lang::get("pms_error.supplier_info_error_30015");
                        break;
                    }
                }
                //物流运费(1:含运费;2:不含运费;3:按区域设置;4:按门店设置;)
                if($logistics_freight == 4){
                    //删除原有信息
                    $shop_list = MaintenanceSupplierLogisticsFreightShop::getShopList($id);
                    if(!empty($shop_list)){
                        $res_shop_del = MaintenanceSupplierLogisticsFreightShop::where('supplier_id', $id)->delete();
                        if(!$res_shop_del){
                            DB::rollback();
                            $response = Lang::get("pms_error.supplier_info_error_30016");
                            break;
                        }
                    }
                    //添加新的门店配置信息
                    $shop_data = [];
                    foreach ($logistics_freight_ext_arr as $v) {
                        $temp = [
                            'supplier_id' => $id,
                            'shop_id' => $v['id'],
                            'logistics_freight' => $v['value'],
                            'created_at' => Common::num2DateTime(time()),
                            'created_by' => $res['user']->id,
                        ];
                        $shop_data[] = $temp;
                    }
                    $res_shop_insert = MaintenanceSupplierLogisticsFreightShop::insert($shop_data);
                    if(!$res_shop_insert){
                        DB::rollback();
                        $response = Lang::get("pms_error.supplier_info_error_30017");
                        break;
                    }
                }
                
                DB::commit();
                PmsOpLog::write('supplier', Input::get("id"),'update', '用户:' . $res['user']->id . ',更改供应商：' . Input::get("id"), json_encode($old), json_encode(MaintenanceSupplier::find($ms->id)), $res['user']->id);
            }catch(Exception $e){
                DB::rollback();
                Log::error("error", array("system" => "pms" ,"event" => "storeOne", 'input' =>Input::all() ,"exception" => $e));
                //echo $e->getMessage();
                $response = Lang::get("pms_error.supplier_update_error_30002");
                break;
            }
            $response['result'] = $ms->id;
        } while (FALSE);
        
        Log::info('info', ['system' => 'pms', 'event' => 'supplier/creatSupplierBusiness', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * 创建供应商的财务信息
     * @param int       $tax              是否含税(1:含税;2:不含税;)
     * @param int       $regular_pay      结算方式 1:是(月结);0:否(现金结算);2:按区域设置;3:按门店设置;
     * @param string    $regular_pay_ext  结算方式扩展信息
     * [{"id":1,"value":0},{"id":2,"value":1}]
     *  $test = [
            [
                'id' => 1,      //城市或者门店ID
                'value' => 0,   //0:现金;1:挂账(月结);
            ],
            [
                'id' => 2,      //城市或者门店ID
                'value' => 1,   //0:现金;1:挂账(月结);
            ],
        ];
     * @link http://api.anhui.com/v1/pms/supplier/creatSupplierLicence?token=3f0641ce3dc3ebb51ef49973fd5e1dd7
     * @link http://api.anhui.com/v1/pms/supplier/creatSupplierLicence?token=3f0641ce3dc3ebb51ef49973fd5e1dd7&id=1&tax=2&regular_pay=3&regular_pay_ext=[{"id":1,"value":0},{"id":2,"value":1}]
     */
    public function creatSupplierLicence(){
        $validator = Validator::make(Input::all(), [
            'token' => 'required',
            'id' => 'required',
            'regular_pay' =>  'required',
            'tax' =>  'required',
            //regular_pay 结算方式 1:是(月结);0:否(现金结算);2:按区域设置;3:按门店设置;
            'regular_pay_ext' => 'required_if:regular_pay,2|required_if:regular_pay,3',
        ]);
        $response = [
            'code' => 0,
            'msg' => 'ok',
        ];
        
        do{
            $response = array('code' => 0, 'msg' => 'ok');
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $id                 = Input::get("id");
            $tax                = Input::get('tax');            //是否含税(1:含税;2:不含税;)
            $regular_pay        = Input::get('regular_pay');    //结算方式 1:是(月结);0:否(现金结算);2:按区域设置;3:按门店设置;
            $regular_pay_ext    = Input::get('regular_pay_ext');//结算方式扩展信息
            $regular_pay_ext_arr = [];    //结算方式扩展信息数组
            if($regular_pay_ext != ''){
                $regular_pay_ext_arr = json_decode($regular_pay_ext, TRUE);
                if(is_array($regular_pay_ext_arr)){
                    foreach ($regular_pay_ext_arr as $v) {
                        if(!in_array($v['value'], [0, 1])){
                            $response = Lang::get("pms_error.supplier_info_error_30023");
                            break 2;
                        }
                    }
                } else {
                    $response = Lang::get("pms_error.supplier_info_error_30022");
                    break;
                }
            }
            if(in_array($regular_pay, [2, 3])){
                if(empty($regular_pay_ext_arr)){
                    $response = Lang::get("pms_error.args_error_100000");
                    break;
                }
            }
            
            $ms = MaintenanceSupplier::find($id);
            if (is_null($ms)){
                $response = Lang::get("pms_error.pms_supplier_error_40032");
                break;
            }

            $old = clone $ms;
            $ms->updated_at = Common::currentTimeString();
            $ms->version += 1;
            
            //财务信息
            $ms->bank = Input::get("bank");//开户行
            $ms->account = Input::get("account");//开户行账号
            $ms->invoice_type = Input::get("invoice_type")?:null;//发票类型 发票类型 1普票  2专票
            $ms->invoice_address = Input::get("invoice_address");//开票地址
            $ms->billing_phone = Input::get("billing_phone");//开票电话
            $ms->taxpayer = Input::get("taxpayer");//纳税人识别号
            
            $ms->gather_bank = Input::get("gather_bank");//收款行名称
            $ms->gather_account = Input::get("gather_account");//收款行账号
            $ms->company_regist_address = Input::get("company_regist_address");//公司注册地址
            $ms->regular_pay = $regular_pay;    //结算方式 1:是(月结);0:否(现金结算);2:按区域设置;3:按门店设置;
            $ms->regular_pay_comment = Input::get("regular_pay_comment");//结款方式备注
            $ms->compare_bill = Input::get("compare_bill");//对账方式
            $ms->bill_day = Input::get("bill_day")?:null;//账期  (天)
            $ms->credit_money = bcmul(Input::get("credit_money"),100,2);//信用额度 单位分
            $ms->tax = $tax;    //是否含税(1:含税;2:不含税;)
            
           try {
                DB::beginTransaction();
                
                $res_ms = $ms->save();
                if(!$res_ms){
                    DB::rollback();
                    $response = Lang::get("pms_error.supplier_update_error_30002");
                    break;
                }
                //结算方式 1:是(月结);0:否(现金结算);2:按区域设置;3:按门店设置;
                if($regular_pay == 2){
                    //删除原有信息
                    $area_list = MaintenanceSupplierPayArea::getAreaList($id);
                    if(!empty($area_list)){
                        $res_area_del = MaintenanceSupplierPayArea::where('supplier_id', $id)->delete();
                        if(!$res_area_del){
                            DB::rollback();
                            $response = Lang::get("pms_error.supplier_info_error_30018");
                            break;
                        }
                    }
                    //添加新的区域配置信息
                    $area_data = [];
                    foreach ($regular_pay_ext_arr as $v) {
                        $temp = [
                            'supplier_id' => $id,
                            'city_id' => $v['id'],
                            'regular_pay' => $v['value'],
                            'created_at' => Common::num2DateTime(time()),
                            'created_by' => $res['user']->id,
                        ];
                        $area_data[] = $temp;
                    }
                    $res_area_insert = MaintenanceSupplierPayArea::insert($area_data);
                    if(!$res_area_insert){
                        DB::rollback();
                        $response = Lang::get("pms_error.supplier_info_error_30019");
                        break;
                    }
                }
                //结算方式 1:是(月结);0:否(现金结算);2:按区域设置;3:按门店设置;
                if($regular_pay == 3){
                    //删除原有信息
                    $shop_list = MaintenanceSupplierPayShop::getShopList($id);
                    if(!empty($shop_list)){
                        $res_shop_del = MaintenanceSupplierPayShop::where('supplier_id', $id)->delete();
                        if(!$res_shop_del){
                            DB::rollback();
                            $response = Lang::get("pms_error.supplier_info_error_30020");
                            break;
                        }
                    }
                    //添加新的门店配置信息
                    $shop_data = [];
                    foreach ($regular_pay_ext_arr as $v) {
                        $temp = [
                            'supplier_id' => $id,
                            'shop_id' => $v['id'],
                            'regular_pay' => $v['value'],
                            'created_at' => Common::num2DateTime(time()),
                            'created_by' => $res['user']->id,
                        ];
                        $shop_data[] = $temp;
                    }
                    $res_shop_insert = MaintenanceSupplierPayShop::insert($shop_data);
                    if(!$res_shop_insert){
                        DB::rollback();
                        $response = Lang::get("pms_error.supplier_info_error_30021");
                        break;
                    }
                }
                DB::commit();
                
                $erp_supplier_id = $this->updateErpSupplier($ms);
                PmsOpLog::write('supplier', Input::get("id"),'update', '用户:' . $res['user']->id . ',更改供应商：' . Input::get("id"), json_encode($old), json_encode(MaintenanceSupplier::find($ms->id)), $res['user']->id);
            }catch(Exception $e){
                DB::rollback();
                Log::error("error", array("system" => "pms" ,"event" => "storeOne", 'input' =>Input::all() ,"exception" => $e));
                echo $e->getMessage();
                $response = Lang::get("pms_error.supplier_update_error_30002");
                break;
            }
            $response['result'] = $ms->id;
        } while (FALSE);
        
        Log::info('info', ['system' => 'pms', 'event' => 'supplier/creatSupplierLicence', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * 同步到pms  anhui库
     * @param obj $ms pms创建的供应商相关信息, array $array erp创建供应商需要的字段
     */
    private function updateErpSupplier($ms) {
            $ms_array = $ms->toArray();
            $ms_array['regular_pay'] = 1;    //同步到ERP平台 统一为 是定期结算  18-9-17 上午11:06
            unset($ms_array['erp_purchase_status']);
            unset($ms_array['erp_id']);
            unset($ms_array['id']);
            unset($ms_array['supplier_class_level']);
            unset($ms_array['tax']);
            unset($ms_array['logistics_freight']);
            $erp_supplier = DB::connection('mysql_data')->table("maintenance_supplier")
                    ->where('id', $ms->erp_id)
                    ->update($ms_array);
            return $erp_supplier;
    }
    
    /**
     * 更新供应商基础信息
     * @param int       $supplier_class_level   供应商分类等级(1:全国级;2:区域级;3:门店级;)
     * @param int       $logistics_freight      物流运费(1:含运费;2:不含运费;3:按区域设置;4:按门店设置;)
     * @param string    $logistics_freight_ext  物流运费扩展信息
     * [{"id":1,"value":1},{"id":2,"value":2}]
     *  $test = [
            [
                'id' => 1,      //城市或者门店ID
                'value' => 1,   //1:含运费;2:不含运费;
            ],
            [
                'id' => 2,      //城市或者门店ID
                'value' => 2,   //1:含运费;2:不含运费;
            ],
        ];
     * @param int       $tax              是否含税(1:含税;2:不含税;)
     * @param int       $regular_pay      结算方式 1:是(月结);0:否(现金结算);2:按区域设置;3:按门店设置;
     * @param string    $regular_pay_ext  结算方式扩展信息
     * [{"id":1,"value":0},{"id":2,"value":1}]
     *  $test = [
            [
                'id' => 1,      //城市或者门店ID
                'value' => 0,   //0:现金;1:挂账(月结);
            ],
            [
                'id' => 2,      //城市或者门店ID
                'value' => 1,   //0:现金;1:挂账(月结);
            ],
        ];
     * @link http://api.anhui.com/v1/pms/supplier/updateSupplier?token=9c3fc0d907f940df788a562b93d5af0c
     */
    function updateSupplier(){
        $validator = Validator::make(Input::all(), [
            'token' => 'required',
            'id' => 'required',
            'name' => 'required',
            'juridical' => 'required',
            'operating_address' => 'required',
            'work_together_type' => 'required',
            'business_type' => 'required',
            //'businss_express' => 'required',
            'regular_pay' =>  'required',
            'supplier_class_level' =>  'required',
            'logistics_freight' => 'required',
            //logistics_freight 物流运费 值为 3:按区域设置;4:按门店设置; 时，物流运费的扩展信息不能为空
            'logistics_freight_ext' => 'required_if:logistics_freight,3|required_if:logistics_freight,4',
            'tax' =>  'required',
            //regular_pay 结算方式 1:是(月结);0:否(现金结算);2:按区域设置;3:按门店设置;
            'regular_pay_ext' => 'required_if:regular_pay,2|required_if:regular_pay,3',
        ]);
        $response = [
            'code' => 0,
            'msg' => 'ok',
        ];
        
        do{
            $response = array('code' => 0, 'msg' => 'ok');
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $id                 = Input::get('id');
            $supplier_class_level   = Input::get('supplier_class_level');   //供应商分类等级(1:全国级;2:区域级;3:门店级;)
            $logistics_freight  = Input::get('logistics_freight');   //物流运费(1:含运费;2:不含运费;3:按区域设置;4:按门店设置;)
            $logistics_freight_ext = Input::get('logistics_freight_ext', '');   //物流运费扩展信息
            $tax                = Input::get('tax');            //是否含税(1:含税;2:不含税;)
            $regular_pay        = Input::get('regular_pay');    //结算方式 1:是(月结);0:否(现金结算);2:按区域设置;3:按门店设置;
            $regular_pay_ext    = Input::get('regular_pay_ext');//结算方式扩展信息
            
            $logistics_freight_ext_arr = [];    //物流运费扩展信息数组
            if($logistics_freight_ext != ''){
                $logistics_freight_ext_arr = json_decode($logistics_freight_ext, TRUE);
                if(is_array($logistics_freight_ext_arr)){
                    foreach ($logistics_freight_ext_arr as $v) {
                        if(!in_array($v['value'], [1, 2])){
                            $response = Lang::get("pms_error.supplier_info_error_30025");
                            break 2;
                        }
                    }
                } else {
                    $response = Lang::get("pms_error.supplier_info_error_30024");
                    break;
                }
            }
            if(in_array($logistics_freight, [3, 4])){
                if(empty($logistics_freight_ext_arr)){
                    $response = Lang::get("pms_error.args_error_100000");
                    break;
                }
            }
            
            $regular_pay_ext_arr = [];    //结算方式扩展信息数组
            if($regular_pay_ext != ''){
                $regular_pay_ext_arr = json_decode($regular_pay_ext, TRUE);
                if(is_array($regular_pay_ext_arr)){
                    foreach ($regular_pay_ext_arr as $v) {
                        if(!in_array($v['value'], [0, 1])){
                            $response = Lang::get("pms_error.supplier_info_error_30023");
                            break 2;
                        }
                    }
                } else {
                    $response = Lang::get("pms_error.supplier_info_error_30022");
                    break;
                }
            }
            if(in_array($regular_pay, [2, 3])){
                if(empty($regular_pay_ext_arr)){
                    $response = Lang::get("pms_error.args_error_100000");
                    break;
                }
            }
            
            //验证是否有相同企业名称
            $name = Input::get("name");
            $supplier = MaintenanceSupplier::where("name",$name)->where('id','<>',$id)->where("status",1)->first();
            if ($supplier){
                $response = Lang::get("pms_error.pms_supplier_error_40031");
                break;
            }
            
            //验证当前是否有相同的社会统一代码
            $licence_credit_num = Input::get('licence_credit_num');
            if ($licence_credit_num != "") {
                $supplier = MaintenanceSupplier::where("licence_credit_num",$licence_credit_num)->where("status",1)->where('id','<>',$id)->first();
                if ($supplier){
                    $response = Lang::get("pms_error.pms_supplier_error_40033");
                    break;
                }
            }
            
            $ms = MaintenanceSupplier::find(Input::get("id"));
            $old = clone $ms;
            $ms->updated_at = Common::currentTimeString();
            $ms->version += 1;
            
            //验证ERP是否有相同企业名称
            $issetErpSupplier = $this->issetErpSupplier($name,$ms->erp_id);
            if (!$issetErpSupplier) {
                $response = Lang::get("pms_error.pms_supplier_error_40029");
                break;
            }
            
            //验证ERP是否有相同的社会统一代码
            if ($licence_credit_num != ""){
                $issetErpCreditNum = $this->issetErpCreditNum($licence_credit_num,$ms->erp_id);
                if (!$issetErpCreditNum) {
                    $response = Lang::get("pms_error.pms_supplier_error_40034");
                    break;
                }
            }
            
            $ms->supplier_class_level = $supplier_class_level;      //供应商分类等级(1:全国级;2:区域级;3:门店级;)
            $ms->name = $name; //公司名称
            $ms->bm = Pinyin::getShortPinyin($name);
            $ms->juridical = Input::get('juridical'); //法定代表人
            $ms->certify_type = Input::get('certify_type')?:null; //证件类型 1身份证  2护照
            $ms->certify_num = Input::get('certify_num')?:null; //证件号码
            $ms->agent = Input::get('agent'); //委托代理人
            $ms->postcode = Input::get('postcode'); //邮编
            $ms->operating_address = Input::get('operating_address'); //营业地址
            $ms->work_together_type = Input::get('work_together_type'); //合作状态 1正常合作  2暂停合作  3终止合作
            if(Input::get('work_together_type') != ''){
                if(Input::get('work_together_type') == 1){
                    $ms->purchase_status = 1;   //采购状态 [0:关闭;1:开启;]
                }else{
                    $ms->purchase_status = 0;
                }    
            }
            
            $ms->car_type = Input::get('car_type');//主营业务
            //营业执照部分
            $ms->licence_name = Input::get('licence_name');//营业执照公司名称
            $ms->licence_credit_num = Input::get('licence_credit_num');//营业执照社会统一信用代码
            $ms->licence_company_type = Input::get('licence_company_type')?:null;//营业执照中的企业类型1有限责任公司2股份有限公司3个人独资4合伙企业
            $ms->licence_juridical = Input::get('licence_juridical');//营业执照法人代表
            $ms->licence_created_time = Input::get('licence_created_time')?:null;//营业执照成立日期
            $ms->licence_home = Input::get('licence_home');//营业执照住所
            $ms->licence_capital = Input::get('licence_capital');//注册资本
            $ms->licence_term_type = Input::get('licence_term_type')?:null;//营业期限类型1短期2长期
            if(Input::get('licence_term_starttime')){
                $ms->licence_term_starttime = Input::get('licence_term_starttime','');//营业期限开始时间
            }
            if(Input::get('licence_term_endtime','')) {
                $ms->licence_term_endtime = Input::get('licence_term_endtime');//营业期限结束时间
            }
            $ms->scope = Input::get('scope');//经营范围
            //业务信息
            $ms->business_type = Input::get("business_type");//业务信息合作方式1铺货2批量采购3临时采购4其他
            $ms->business_type_comment = Input::get("business_type_comment");//合作方式为"其他“时候。合作方式名
            $ms->business_rebate_policy = Input::get("business_rebate_policy");//返利政策
            //$ms->businss_express = Input::get("businss_express");//物流信息1安惠配送2供应商配送3第三方物流
            $ms->business_activity = Input::get("business_activity");//市场活动策划
            $ms->business_train = Input::get("business_train");//培训支持
            $ms->after_sale = Input::get("after_sale");//售后质保
            $ms->scope = Input::get('scope');//经营范围
            $ms->logistics_freight = $logistics_freight;        //物流运费(1:含运费;2:不含运费;3:按区域设置;4:按门店设置;)
            //财务信息
            $ms->bank = Input::get("bank");//开户行
            $ms->account = Input::get("account");//开户行账号
            $ms->invoice_type = Input::get("invoice_type")?:null;//发票类型 发票类型 1普票  2专票
            $ms->invoice_address = Input::get("invoice_address");//开票地址
            $ms->billing_phone = Input::get("billing_phone");//开票电话
            $ms->taxpayer = Input::get("taxpayer");//纳税人识别号
            $ms->gather_bank = Input::get("gather_bank");//收款行名称
            $ms->gather_account = Input::get("gather_account");//收款行账号
            $ms->company_regist_address = Input::get("company_regist_address");//公司注册地址
            $ms->regular_pay = $regular_pay;    //结算方式 1:是(月结);0:否(现金结算);2:按区域设置;3:按门店设置;
            $ms->regular_pay_comment = Input::get("regular_pay_comment");//结款方式备注
            $ms->compare_bill = Input::get("compare_bill");//对账方式
            $ms->bill_day = Input::get("bill_day")?:null;//账期  (天)
            $ms->credit_money = bcmul(Input::get("credit_money"),100,2);//信用额度 单位分
            $ms->tax = $tax;    //是否含税(1:含税;2:不含税;)

            try {
                DB::beginTransaction();
                $res_ms = $ms->save();
                if(!$res_ms){
                    DB::rollback();
                    $response = Lang::get("pms_error.supplier_update_error_30002");
                    break;
                }
                //物流运费(1:含运费;2:不含运费;3:按区域设置;4:按门店设置;)
                if($logistics_freight == 3){
                    //删除原有信息
                    $area_list = MaintenanceSupplierLogisticsFreightArea::getAreaList($id);
                    if(!empty($area_list)){
                        $res_area_del = MaintenanceSupplierLogisticsFreightArea::where('supplier_id', $id)->delete();
                        if(!$res_area_del){
                            DB::rollback();
                            $response = Lang::get("pms_error.supplier_info_error_30014");
                            break;
                        }
                    }
                    //添加新的区域配置信息
                    $area_data = [];
                    foreach ($logistics_freight_ext_arr as $v) {
                        $temp = [
                            'supplier_id' => $id,
                            'city_id' => $v['id'],
                            'logistics_freight' => $v['value'],
                            'created_at' => Common::num2DateTime(time()),
                            'created_by' => $res['user']->id,
                        ];
                        $area_data[] = $temp;
                    }
                    $res_area_insert = MaintenanceSupplierLogisticsFreightArea::insert($area_data);
                    if(!$res_area_insert){
                        DB::rollback();
                        $response = Lang::get("pms_error.supplier_info_error_30015");
                        break;
                    }
                }
                //物流运费(1:含运费;2:不含运费;3:按区域设置;4:按门店设置;)
                if($logistics_freight == 4){
                    //删除原有信息
                    $shop_list = MaintenanceSupplierLogisticsFreightShop::getShopList($id);
                    if(!empty($shop_list)){
                        $res_shop_del = MaintenanceSupplierLogisticsFreightShop::where('supplier_id', $id)->delete();
                        if(!$res_shop_del){
                            DB::rollback();
                            $response = Lang::get("pms_error.supplier_info_error_30016");
                            break;
                        }
                    }
                    //添加新的门店配置信息
                    $shop_data = [];
                    foreach ($logistics_freight_ext_arr as $v) {
                        $temp = [
                            'supplier_id' => $id,
                            'shop_id' => $v['id'],
                            'logistics_freight' => $v['value'],
                            'created_at' => Common::num2DateTime(time()),
                            'created_by' => $res['user']->id,
                        ];
                        $shop_data[] = $temp;
                    }
                    $res_shop_insert = MaintenanceSupplierLogisticsFreightShop::insert($shop_data);
                    if(!$res_shop_insert){
                        DB::rollback();
                        $response = Lang::get("pms_error.supplier_info_error_30017");
                        break;
                    }
                }
                
                //结算方式 1:是(月结);0:否(现金结算);2:按区域设置;3:按门店设置;
                if($regular_pay == 2){
                    //删除原有信息
                    $area_list = MaintenanceSupplierPayArea::getAreaList($id);
                    if(!empty($area_list)){
                        $res_area_del = MaintenanceSupplierPayArea::where('supplier_id', $id)->delete();
                        if(!$res_area_del){
                            DB::rollback();
                            $response = Lang::get("pms_error.supplier_info_error_30018");
                            break;
                        }
                    }
                    //添加新的区域配置信息
                    $area_data = [];
                    foreach ($regular_pay_ext_arr as $v) {
                        $temp = [
                            'supplier_id' => $id,
                            'city_id' => $v['id'],
                            'regular_pay' => $v['value'],
                            'created_at' => Common::num2DateTime(time()),
                            'created_by' => $res['user']->id,
                        ];
                        $area_data[] = $temp;
                    }
                    $res_area_insert = MaintenanceSupplierPayArea::insert($area_data);
                    if(!$res_area_insert){
                        DB::rollback();
                        $response = Lang::get("pms_error.supplier_info_error_30019");
                        break;
                    }
                }
                //结算方式 1:是(月结);0:否(现金结算);2:按区域设置;3:按门店设置;
                if($regular_pay == 3){
                    //删除原有信息
                    $shop_list = MaintenanceSupplierPayShop::getShopList($id);
                    if(!empty($shop_list)){
                        $res_shop_del = MaintenanceSupplierPayShop::where('supplier_id', $id)->delete();
                        if(!$res_shop_del){
                            DB::rollback();
                            $response = Lang::get("pms_error.supplier_info_error_30020");
                            break;
                        }
                    }
                    //添加新的门店配置信息
                    $shop_data = [];
                    foreach ($regular_pay_ext_arr as $v) {
                        $temp = [
                            'supplier_id' => $id,
                            'shop_id' => $v['id'],
                            'regular_pay' => $v['value'],
                            'created_at' => Common::num2DateTime(time()),
                            'created_by' => $res['user']->id,
                        ];
                        $shop_data[] = $temp;
                    }
                    $res_shop_insert = MaintenanceSupplierPayShop::insert($shop_data);
                    if(!$res_shop_insert){
                        DB::rollback();
                        $response = Lang::get("pms_error.supplier_info_error_30021");
                        break;
                    }
                }
                DB::commit();
                
                $erp_supplier_id = $this->updateErpSupplier($ms);
                PmsOpLog::write('supplier', Input::get("id"),'update', '用户:' . $res['user']->id . ',更改供应商：' . Input::get("id"), json_encode($old), json_encode(MaintenanceSupplier::find($ms->id)), $res['user']->id);
               
            }catch(Exception $e){
                DB::rollback();
                Log::error("error", array("system" => "pms" ,"event" => "updateSupplier", 'input' =>Input::all() ,"exception" => $e));
                //echo $e->getMessage();
                $response = Lang::get("pms_error.supplier_update_error_30002");
                break;
            }
            $response['result'] = $ms->id;
        } while (FALSE);
        
        Log::info('info', ['system' => 'pms', 'event' => 'supplier/updateSupplier', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * 新建和修改供应商联系人信息
     */
    public function linkManStore(){
        $validator = Validator::make(Input::all(), [
            'token' => 'required',
            'supplier_id' => 'required'
        ]);
        do{
            $response = array('code' => 0, 'msg' => 'ok');
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $id = Input::get("id");
            if(Input::get("id") && Input::get("id") != ''){
                $supplier = MaintenanceSupplier::find(Input::get("id")); //供应商是否存在
                if (!$supplier){
                    $response = Lang::get("supplier_not_exit_error_30001");
                    break;
                }
                $slm = SupplierLinkMan::find(Input::get("id"));
                $slm->updated_at = Common::currentTimeString();
            }else{
                $slm = new SupplierLinkMan();
                $slm->created_at = Common::currentTimeString();
                $slm->updated_at = Common::currentTimeString();
                $slm->create_by = $res['user']->id;
            } 
            
            $slm->supplier_id = Input::get("supplier_id");//经销商id
            $slm->name = Input::get("name");//姓名
            $slm->position = Input::get("position");//职位
            $slm->telephone = Input::get("telephone");//座机电话
            $slm->mobile = Input::get("mobile");//手机电话
            $slm->mail = Input::get("mail");//电子邮箱
            $slm->shop_show = Input::get("shop_show");//门店是否可见  1可见  0不可见
            $slm->tag_show = Input::get("tag_show");//可见页签 1公司信息   2财务信息   3合同信息(格式可以为 1,2,3)
            $slm->status = 1;//是否有效
            $slm->comment = Input::get("comment");//备注
            $slm->save();
            $response['result'] = $slm->id;
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "linkManStore", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * 展示联系人信息
     */
    public function linkManList(){
        $validator = Validator::make(Input::all(), [
            'token' => 'required',
            'supplier_id' => 'required',
        ]);
        do{
            $response = array('code' => 0, 'msg' => 'ok');
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $supplier_id = Input::get("supplier_id");
            $supplier = MaintenanceSupplier::find($supplier_id); //供应商是否存在
            if (!$supplier){
                $response = Lang::get("supplier_not_exit_error_30001");
                break;
            }
            
            $sql = "select * from supplier_linkman where supplier_id = {$supplier_id} and status=1";
            
            $tag = Input::get("tag");//可见页签 1公司信息   2财务信息   3合同信息(格式为 1,2,3)
            if ($tag) $sql .= " and FIND_IN_SET('{$tag}',tag_show) ";
            $sql .= " order by id";
            $slm = DB::select($sql);
            $response['result'] = $slm;
            
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "linkManList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * 删除联系人
     */
    public function linkManDel(){
        $validator = Validator::make(Input::all(), [
            'token' => 'required',
            'id' => 'required',
        ]);
        do{
            $response = array('code' => 0, 'msg' => 'ok');
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $slm = SupplierLinkMan::find(Input::get("id"));
            $slm = SupplierLinkMan::where("status",1)->find(Input::get("id"));
            if (!$slm) {
                $response = Lang::get("pms_error.pms_supplier_error_40035");
                break;
            }
            $slm->updated_at = Common::currentTimeString();
            $slm->status = 0;
            $slm->save();
            $response['result'] = 'OK';
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "linkManDel", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * 联系人是否可见配置
     */
    public function linkManShow(){
        $validator = Validator::make(Input::all(), [
            'token' => 'required',
            'id' => 'required',
        ]);
        do{
            $response = array('code' => 0, 'msg' => 'ok');
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $slm = SupplierLinkMan::where("status",1)->find(Input::get("id"));
            if (!$slm) {
                $response = Lang::get("pms_error.pms_supplier_error_40035");
                break;
            }
            $slm->updated_at = Common::currentTimeString();
            $slm->shop_show = Input::get("shop_show");//门店是否可见  1可见  0不可见
            $slm->tag_show = Input::get("tag_show");//可见页签 1公司信息   2财务信息   3合同信息(格式可以为 1,2,3)
            $slm->save();
            $response['result'] = 'OK';
        }while(false);
        Log::info("info", array("system" => "pms" ,"event" => "linkManShow", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
}